package com.winona.code;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.widget.Toast;

import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.core.LocalFileManager;
import com.taplinker.client.domain.UserInfo;
import com.taplinker.client.im.SocketTemplateContext;
import com.taplinker.client.im.rpc.SwitchToken;
import com.taplinker.core.rpc.Result;
import com.taplinker.core.rpc.RpcClientContext;
import com.taplinker.core.rpc.command.SimpleBaseCommand;
import com.taplinker.core.rpc.http.HttpTemplate;
import com.taplinker.core.util.json.JsonUtil;
import com.winona.ConstantValue;
import com.winona.HomeActivity;
import com.winona.bean.Expert;
import com.winona.bean.User;
import com.winona.ui.Welcome;
import com.winona.widget.LoadingDialog;

public class LoginCmd extends SimpleBaseCommand {
	private String username;
	private String password;
	private String code;
	private String codetoken;

	private LoadingDialog dialog;
	private boolean relogin = false;

	public LoginCmd(Context ctx, LoadingDialog dialog, String username,
			String password, boolean relogin) {
		this(ctx, dialog, username, password, null, null, relogin);
	}

	public LoginCmd(Context ctx, String username, String password, String code,
			String codetoken, boolean relogin) {
		this(ctx, null, username, password, code, codetoken, relogin);
	}

	public LoginCmd(Context ctx, LoadingDialog dialog, String username,
			String password, String code, String codetoken, boolean relogin) {
		super(ctx);
		this.dialog = dialog;
		this.username = username;
		this.password = password;
		this.code = code;
		this.codetoken = codetoken;
		this.relogin = relogin;
	}

	@Override
	public Result go() {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("body.username", username);
		params.put("body.password", password);
		if (!TextUtils.isEmpty(code) && !TextUtils.isEmpty(codetoken)) {
			params.put("code", code);
			params.put("codeToken", codetoken);
		}
		return new HttpTemplate().postForForm(ConstantValue.COMMON
				+ ConstantValue.LOGIN, params);
	}

	@Override
	public void yes(Result result) {
		if (dialog != null) {
			dialog.dismiss();
		}

		try {
			JSONObject jo = new JSONObject(result.object.toString());
			User user1 = JsonUtil
					.jsonToObject(jo.getString("body"), User.class);

			UserInfo user = new UserInfo();
			user.setUserName(user1.getExpert().getUsername());
			user.setUserIcon(user1.getExpert().getHead());
			user.setToken(user1.getToken());

			user.setId(Long.valueOf(user1.getExpert().getId()));
			user.setUserid(Long.valueOf(user1.getExpert().getUserid()));

			user.setImToken(user1.getToken());
			user.setNickname(user1.getExpert().getName());

			Expert expert = new Expert();
			expert.setHead(user1.getExpert().getHead());
			expert.setPhysicianCertificate(user1.getExpert()
					.getPhysicianCertificate());
			expert.setIdentification(user1.getExpert().getIdentification());
			expert.setPosition(user1.getExpert().getPosition());
			expert.setPhone(user1.getExpert().getPhone());
			expert.setMail(user1.getExpert().getMail());
			expert.setSexual(user1.getExpert().getSexual());

			AppConfigFactory
					.getInstance()
					.setAppKey(
							"19581e27de7ced00ff1ce50b2047e7a567c76b1cbaebabe5ef03f7c3017bb5b7");
			AppConfigFactory.getInstance().setUserInfo(user);
			AppConfigFactory.getInstance().setExpert(expert);
			saveUserInfo();

			LocalFileManager.getInstance().ayscCreateDirs();
			RpcClientContext.getInstance().setCookies(
					"TAPLINKER_TOKEN=" + user.getToken());
			SocketTemplateContext.getInstance().initialize(
					context.getApplicationContext());

			// 初始化左侧导航栏
			// Intent intent = null;
			// intent = new Intent(super.context, HomeActivity.class);
			 new SwitchToken().execute();

			if (relogin) {
				super.context.startActivity(new Intent(super.context,
						HomeActivity.class));
			}
			((Activity) super.context).startActivity(new Intent(super.context,
					HomeActivity.class));

		} catch (Exception e) {
			e.printStackTrace();
			no(result);

		}

	}

	private void saveUserInfo() {
		if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
			return;
		}
		try {
			Editor editor = super.context.getSharedPreferences(
					Welcome.SP_FILE_NAME, Context.MODE_PRIVATE).edit();
			editor.putString(Welcome.SP_KEY_USERNAME, username);
			editor.putString(Welcome.SP_KEY_PASSWORD, password);
			editor.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void no(Result result) {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		try {
			if (!TextUtils.isEmpty(result.message)) {
				Toast.makeText(super.context, result.message,
						Toast.LENGTH_SHORT).show();
				return;
			}
			String message = new JSONObject(result.object.toString())
					.getString("message");
			if (!TextUtils.isEmpty(message) && !"null".equals(message)) {
				Toast.makeText(super.context, message, Toast.LENGTH_SHORT)
						.show();
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Toast.makeText(super.context, "登录失败, 请重试", Toast.LENGTH_SHORT).show();
	}
}
